<?php


namespace app\zyhsapi\model;


use app\common\lib\exception\ApiException;
use think\Exception;
use XznsTools\cache\zyhs\CacheManageZyhs;

class ZyhsUserPush extends BaseCacheZyhs
{
    protected $table = 'good_wechat.zyhs_user_push';

    protected $cacheModel = 'user.push_regid';

    /**
     * 获取用户推送设备ID
     * @param int $uid
     * @return array
     * @throws \Exception
     */
    public function getUserRegid(int $uid): array
    {
        $userPushData = CacheManageZyhs::getInstance()->setCacheConfig($this->cacheModel, $uid)->getDataAndSet(function () use ($uid)
        {
            try
            {
                $data = $this->where('uid', $uid)->findOrFail()->toArray();
            }
            catch (Exception $e)
            {
                // \think\Log::write('获取用户推送设备ID失败，ZyhsUserPush->getUserRegid()：' . $e->getMessage(), 'error');
                $data = [];
            }

            return $data ?: [''];
        });

        if (array_filter($userPushData))
        {
            return arrayKeyData2int($userPushData, ['id', 'uid', 'push_type', 'type', 'status', 'msg_status']);
        } else
        {
            return [];
        }
    }

    /**
     * 获取用户 是否允许回复我的状态 true 允许 false 不允许
     * @param int $uid
     * @return bool
     * @throws \Exception
     */
    public function getUserReplyStatus(int $uid): bool
    {
        $pushInfo = $this->getUserRegid($uid);

        $replySrarts = (int)($pushInfo['reply_status'] ?? 1); // 1开启 2关闭 0默认开启

        return $replySrarts !== 2; // 不等于关闭 则为开启
    }

    public function Del(int $uid)
    {
        try
        {
            $this->where(['uid' => $uid])->delete();

            CacheManageZyhs::getInstance()->setCacheConfig($this->cacheModel, $uid)->rmCache();
        }
        catch (\Exception $e)
        {
            \think\Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
        }
    }

    /**
     * 推送绑定
     * @param array $data
     * @param int $uid
     * @throws ApiException
     * @throws \Exception
     */
    public function pushBindNew(array $data, int $uid)
    {
        $userPushData = $this->getUserRegid($uid);
        try
        {
            if ($userPushData)
            {
                $this->where('id', $userPushData['id'])->update($data);
                CacheManageZyhs::getInstance()->setCacheConfig($this->cacheModel, $uid)->setCache($data);
            } else
            {
                $data['uid'] = $uid;
                self::create($data);
                CacheManageZyhs::getInstance()->setCacheConfig($this->cacheModel, $uid)->rmCache();
            }
        }
        catch (\Exception $e)
        {
            throw new ApiException('推送绑定失败', 200, config('code.error'));
        }
    }
}
